<template>
  <div class="woker-list">
    <div class="main-container">
      <div class="top-bar">
        <el-button type="primary" @click="onCreateWokerClick">添加师傅</el-button>
      </div>
      <div class="content">
        <el-table
          stripe
          :data="filterTableData"
          style="width: 100%"
        >
          <el-table-column label="名称" prop="nickname" width="120px" />
          <el-table-column label="性别" prop="genderName" width="120px" />
          <el-table-column label="年龄" prop="age" width="120px" />
          <el-table-column label="技能" prop="skill" width="300px" />
          <el-table-column label="创建时间" prop="createTime" width="200px" />
          <el-table-column label="创建人" prop="createUser" width="120px" />
          <el-table-column align="right" width="160px">
            <template #header>
              <el-input v-model="search" placeholder="师傅搜索" />
            </template>
            <template #default="scope">
              <el-button @click="handleEdit(scope.$index, scope.row)">
                编辑
              </el-button>
              <el-button
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-show="!tableData || tableData.length === 0" description="暂无数据" />
      </div>
      <el-dialog v-model="dialogFormVisible" title="添加师傅" width="500" @close="handleCancelAdd">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item label="名称" prop="name" :required="false">
            <el-input v-model="form.name" autocomplete="off" placeholder="请输入师傅名称" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio value="1" size="small">男</el-radio>
              <el-radio value="0" size="small">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="form.age" autocomplete="off" placeholder="请输入师傅年龄" type="number" />
          </el-form-item>
          <el-form-item label="工作经验 (年)" prop="workingAge">
            <el-input v-model="form.workingAge" autocomplete="off" placeholder="请输入工作经验年限" type="number" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobilePhone">
            <el-input v-model="form.mobilePhone" autocomplete="off" placeholder="请输入手机号码 (同名时方便区分)" type="number" />
          </el-form-item>
          <el-form-item label="技能" prop="skill">
            <el-input v-model="form.skill" autocomplete="off" placeholder="请输入技能 (使用“,”分隔，如“保洁,修空调,地暖清洁”)" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCancelAdd">取消</el-button>
            <el-button type="primary" @click="handleCreateWoker(formRef)">确认</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="dialogEditFormVisible" title="编辑师傅" width="500" @close="handleCancelEdit">
        <el-form :model="editForm" :rules="editRules" ref="editFormRef">
          <el-form-item label="名称" prop="name" :required="false">
            <el-input v-model="editForm.name" autocomplete="off" placeholder="请输入师傅名称" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="editForm.gender">
              <el-radio value="1" size="small">男</el-radio>
              <el-radio value="0" size="small">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="editForm.age" autocomplete="off" placeholder="请输入师傅年龄" type="number" />
          </el-form-item>
          <el-form-item label="工作经验 (年)" prop="workingAge">
            <el-input v-model="editForm.workingAge" autocomplete="off" placeholder="请输入工作经验年限" type="number" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobilePhone">
            <el-input v-model="editForm.mobilePhone" autocomplete="off" placeholder="请输入手机号码 (同名时方便区分)" type="number" />
          </el-form-item>
          <el-form-item label="技能" prop="skill">
            <el-input v-model="editForm.skill" autocomplete="off" placeholder="请输入技能 (使用“,”分隔，如“保洁,修空调,地暖清洁”)" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCancelEdit">取消</el-button>
            <el-button type="primary" @click="handleEditWoker(editFormRef)">提交</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="centerDialogVisible" title="提示" width="300" center>
        <div class="delete-text">
          是否删除师傅 {{ currentSelectedWoker ? currentSelectedWoker.name : '' }}
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCancelDelete">取消</el-button>
            <el-button type="primary" @click="handleDeleteClick">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { onMounted, computed, ref, reactive, watch } from 'vue'
import useWokersStore from '@/store/wokers/wokers'
import { format, parseISO } from 'date-fns'

const wokersStore = useWokersStore()
const dialogFormVisible = ref(false)
const dialogEditFormVisible = ref(false)
const centerDialogVisible = ref(false)
const formRef = ref(null)
const editFormRef = ref(null)
const currentSelectedWoker = ref(null)

watch(currentSelectedWoker, (newValue, oldValue) => {
  if (newValue) {
    editForm.id = newValue.id
    editForm.name = newValue.name
    editForm.gender = String(newValue.gender)
    editForm.age = String(newValue.age)
    editForm.workingAge = String(newValue.workingAge)
    editForm.mobilePhone = newValue.mobilePhone
    editForm.skill = newValue.skill
  } else {
    editForm.id = ''
    editForm.name = ''
    editForm.gender = '1'
    editForm.age = ''
    editForm.workingAge = ''
    editForm.mobilePhone = ''
    editForm.skill = ''
  }
}, { deep: true })

const form = reactive({
  name: '',
  gender: '1',
  age: '',
  workingAge: '',
  mobilePhone: '',
  skill: ''
})

const editForm = reactive({
  id: '',
  name: '',
  gender: '1',
  age: '',
  workingAge: '',
  mobilePhone: '',
  skill: ''
})

const rules = reactive({
  name: [
    { required: true, message: '请输入师傅名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ]
})

const editRules = reactive({
  name: [
    { required: true, message: '请输入师傅名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ]
})

const handleCancelAdd = () => {
  dialogFormVisible.value = false
  resetFrom()
}

const handleCancelEdit = () => {
  dialogEditFormVisible.value = false
  currentSelectedWoker.value = null
}

const handleCancelDelete = () => {
  centerDialogVisible.value = false
  currentSelectedWoker.value = null
}

const resetFrom = () => {
  form.name = ''
  form.gender = '1'
  form.age = ''
  form.workingAge = ''
  form.mobilePhone = ''
  form.skill = ''
}

const tableData = ref([])

const loadWokers = () => {
  wokersStore.getWokers({
    limit: 50,
    offset: 0
  }).then((res) => {
    if (res.code === 0) {
      tableData.value = res.data.map((woker) => {
        return {
          ...woker,
          nickname: woker.name,
          createUser: woker.creator.nickname,
          genderName: woker.gender == '1' ? '男' : '女',
          createTime: format(parseISO(woker.createTime), 'yyyy-MM-dd HH:mm:ss')
        }
      })
    }
    console.log(res)
  }).catch((err) => {
    if (err) console.log(err)
  })
}

const handleEditWoker = (formEl) => {
  const validateForm = () => {
    return new Promise((resolve, reject) => {
      formEl.validate((valid) => {
        if (valid) {
          resolve(true)
        } else {
          reject(false)
        }
      })
    })
  }

  validateForm().then(() => {
    const params = {
      id: editForm.id,
      name: editForm.name,
      gender: editForm.gender,
      age: editForm.age,
      working_age: editForm.workingAge,
      mobile_phone: editForm.mobilePhone,
      skills: editForm.skill
    }

    console.log('params: ', params)
    wokersStore.updateWoker(params).then((res) => {
      console.log('wokersStore.updateWoker: ', res)
      if (res.code === 0) {
        dialogEditFormVisible.value = false
        loadWokers()
        ElMessage({
          message: '编辑师傅成功 ~',
          type: 'success'
        })
      } else {
        ElMessage({
          message: res.message,
          type: 'error'
        })
      }
    })
  })
}

const handleDeleteClick = () => {
  wokersStore.deleteWoker(currentSelectedWoker.value.id).then((res) => {
    if (res.code === 0) {
      currentSelectedWoker.value = null
      centerDialogVisible.value = false
      loadWokers()
      ElMessage({
        message: '删除师傅成功 ~',
        type: 'success'
      })
    } else {
      ElMessage({
        message: res.message,
        type: 'error'
      })
    }
  })
}

const handleCreateWoker = (formEl) => {
  const validateForm = () => {
    return new Promise((resolve, reject) => {
      formEl.validate((valid) => {
        if (valid) {
          resolve(true)
        } else {
          reject(false)
        }
      })
    })
  }

  validateForm().then(() => {
    const params = {
      name: form.name,
      gender: form.gender,
      age: form.age,
      working_age: form.workingAge,
      mobile_phone: form.mobilePhone,
      skills: form.skill
    }
    console.log('params: ', params)
    wokersStore.createWoker(params).then((res) => {
      console.log('wokersStore.createWoker: ', res)
      if (res.code === 0) {
        dialogFormVisible.value = false
        resetFrom()
        loadWokers()
        ElMessage({
          message: '添加师傅成功 ~',
          type: 'success'
        })
      } else {
        ElMessage({
          message: res.message,
          type: 'error'
        })
      }
    }).catch((error) => {
      if (error) console.log(error)
    })
  }).catch((error) => {
    if (error) console.log(error)
  })
}

const search = ref('')
const filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !search.value ||
      data.nickname.toLowerCase().includes(search.value.toLowerCase())
  )
)
const handleEdit = (index, row) => {
  currentSelectedWoker.value = row
  dialogEditFormVisible.value = true
}
const handleDelete = (index, row) => {
  currentSelectedWoker.value = row
  centerDialogVisible.value = true
}

const onCreateWokerClick = () => {
  dialogFormVisible.value = true
}

onMounted(() => {
  loadWokers()
})

</script>

<style lang="scss" scoped>

.woker-list {
  .main-container {
    .top-bar {
      padding: 10px 10px 20px;
      border-bottom: 1px solid #ededed;
    }
    .content {
      margin-top: 20px;
    }
  }
}

</style>